import json

from http_server import Response

CONF_FILE = 'config.json'


class Config:
    def __init__(self):
        self.conf = {}

    def load(self):
        with open(CONF_FILE) as f:
            conf_str = f.read()
        print('ReadConf:', conf_str)
        self.conf = json.loads(conf_str)

    def get(self, names, default=None):
        parent = self.conf
        for name in names:
            if name not in parent:
                return default
            parent = parent[name]
            if not isinstance(parent, dict):
                return parent
        return parent


class ConfigController:
    def post(self, req):
        body = req.body
        print('Write config:', body)
        with open(CONF_FILE, 'w') as f:
            f.write(body.read_all_as_string())
        return Response(status=200, body=CONF_FILE)

